package cc.miwuya.owner.controller;

import cc.miwuya.common.util.JwtUtils;
import cc.miwuya.common.util.Result;
import cc.miwuya.community.domain.RoleUser;
import cc.miwuya.complain.domain.Complain;
import cc.miwuya.core.BaseController;
import cc.miwuya.owner.client.*;
import cc.miwuya.owner.domain.User;
import cc.miwuya.owner.service.UserService;
import cc.miwuya.property.domain.Repair;
import cc.miwuya.property.domain.Shops;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 迷雾森林
 * @Date 2024-02-24 11:10
 */
@RestController
@RequestMapping("/owner")
public class OwnerController extends BaseController {

    @Resource
    UserService userService;
    @Resource
    RoleClient roleClient;
    @Resource
    HouseClient houseClient;
    @Resource
    ShopsClient shopsClient;
    @Resource
    ResidentialClient residentialClient;
    @Resource
    ComplainClient complainClient;
    @Resource
    PropertyClient propertyClient;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        User username = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (username != null) {
            return Result.error("当前用户名已存在");
        }
        user.setPassword(DigestUtil.sha256Hex(user.getPassword()));
        boolean save = userService.save(user);
        return Result.success(save);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        System.out.println(user);
        User username = getUserByUsername(user.getUsername());
        if (username == null) {
            return Result.error(401, "当前用户名或密码错误");
        }
        if (!username.getPassword().equals(DigestUtil.sha256Hex(user.getPassword()))) {
            return Result.error(401, "当前用户名或密码错误");
        }
        List<RoleUser> role = roleClient.getUserRoleByUsername(user.getUsername());
        HashMap<String, Object> builder = new HashMap<>();
        List<Long> list = new ArrayList<>();
        for (RoleUser roleUser : role) {
            list.add(roleUser.getId());
        }
        builder.put("role", list);
        builder.put("username", username.getUsername());
        builder.put("userId", username.getId());
        //Map<String, Object> builder = MapUtil.builder().put("role", role).put("username", username).build();
        String token = JwtUtils.generateToken(username.getId(), "community", builder);

        Map<Object, Object> map = MapUtil.builder()
                .put("role", list)
                .put("username", username.getUsername())
                .put("token", token)
                .build();
        return Result.success(map);

    }

    /**
     * 重置用户密码
     */
    @PostMapping("/edit/password")
    public Result editUserPassword(@RequestBody Map<String, Object> map) {
        String username = map.get("username").toString();
        String password = map.get("password").toString();
        String newPassword = map.get("newPassword").toString();
        String reNewPassword = map.get("reNewPassword").toString();
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        if (user.getPassword().equals(DigestUtil.sha256Hex(password))) {
            if (newPassword.equals(reNewPassword)) {
                user.setPassword(DigestUtil.sha256Hex(newPassword));
                userService.updateById(user);
                return Result.success("重置成功");
            }
            return Result.error("两次新密码不匹配");
        }
        return Result.error("原密码错误！");
    }

    /**
     * 获取名下房产
     */
    @GetMapping("/house/list")
    public Result ownerHouse(Long residentialId) {
        Long currentUsrId = userService.getCurrentUsrId();
        return houseClient.getOwnerHouseList(currentUsrId, residentialId);
    }

    /**
     * 根据用户ID获取名下房产
     */
    @GetMapping("/getUserHouseList/{userId}")
    public Result getUserHouseList(@PathVariable Long userId, Long residentialId) {
        return houseClient.getOwnerHouseList(userId, residentialId);
    }

    /**
     * 根据用户ID获取用户信息
     */
    @GetMapping("/ownerInfo/{ownerId}")
    public Result ownerInfo(@PathVariable Long ownerId) {
        return Result.success(userService.getById(ownerId));
    }

    @GetMapping("/getCurrentId")
    public Long getCurrentId() {
        return userService.getCurrentUsrId();
    }

    /**
     * 根据用户名获取用户
     */
    @GetMapping("/getUser/{username}")
    public User getUserByUsername(@PathVariable String username) {
        System.out.println(username);
        return userService.getUserByUsername(username);
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/getUserList")
    public Result getUserList(String username) {
        return Result.success(userService.getPage(getPage(), username));
    }

    /**
     * 根据用户ID获取用户角色
     */
    @GetMapping("/getUserRole/{id}")
    public Result getUserRole(@PathVariable Long id) {
        return Result.success(userService.getUserRole(id));
    }

    /**
     * 根据用户名重置密码
     */
    @GetMapping("/rePassword/{userId}")
    public Result setUserPasswordByUserId(@PathVariable Long userId) {
        User user = userService.getById(userId);
        user.setPassword(DigestUtil.sha256Hex("Community123456."));
        userService.updateById(user);
        return Result.success("密码重置为Community123456.");
    }

    /**
     * 获取用户名下所有商铺
     */
    @GetMapping("/getUserShopsList")
    public Result getUserShopsList(String name) {
        return shopsClient.getOwnerShopsList(getCurrentId(), name);
    }

    /**
     * 获取当前用户有权限操作的所有小区
     */
    @GetMapping("/getResidentialList")
    public Result getResidentialList() {
        return Result.success(residentialClient.getResidentialList().getData());
    }

    /**
     * 根据小区获取业主所有房屋
     */
    @GetMapping("/getOwnerHouseList")
    public Result getOwnerHouseList(Long residentialId) {
        System.out.println(getCurrentId());
        return houseClient.getOwnerHouseList(getCurrentId(), residentialId);
    }

    /**
     * 根据房屋ID和计量表类型获取计量表列表
     */
    @GetMapping("/getMeterList")
    public Result getMeterList(Long houseId, String meterType) {
        if (StrUtil.isEmpty(meterType) || meterType.equals("null")) {
            meterType = "-1";
        }
        return houseClient.getOwnerMeterList(houseId, Integer.parseInt(meterType));
    }

    /**
     * 编辑名下商铺信息
     */
    @PostMapping("/shops/edit")
    public Result editShops(@RequestBody Shops shops) {
        System.out.println(shops);
        shopsClient.editShops(shops);
        return Result.success();
    }

    /**
     * 获取名下车位列表
     */
    @GetMapping("/parking/list")
    public Result getParkingList(String name) {
        return Result.success(shopsClient.listByOwner(getCurrentId(), name).getData());
    }

    /**
     * 获取投诉列表
     */
    @GetMapping("/repair/list")
    public Result getRepairList(String name, Long residentialId) {
        return Result.success(houseClient.getOwnerRepairList(name, residentialId, getCurrentId()).getData());
    }
    @PostMapping("/repair/add")
    public Result addRepair(@RequestBody Repair repair){
        repair.setCreated(LocalDateTime.now());
        repair.setUserId(getCurrentId());
        repair.setStatus(0);
        return houseClient.edit(repair);
    }

    @GetMapping("/complain/list")
    public Result getComplainList(String name, Long residentialId) {
        return Result.success(complainClient.getOwnerComplainList(residentialId, name, getCurrentId()).getData());
    }

    @PostMapping("/complain/score")
    public Result scoreComplain(@RequestBody Complain complain) {
        return Result.success(complainClient.scoreComplain(complain));
    }

    /**
     * 获取所有物业
     */
    @GetMapping("/getAdmin")
    public Result getAdmin() {
        return Result.success(propertyClient.listAll().getData());
    }

    /**
     * 发布投诉
     */
    @PostMapping("/addComplain")
    public Result addComplain(@RequestBody Complain complain) {
        complain.setUserId(getCurrentId());
        return Result.success(complainClient.edit(complain));
    }

    @GetMapping("/deleteComplain/{complainId}")
    public Result deleteComplain(@PathVariable Long complainId) {
        complainClient.delete(complainId);
        return Result.success();
    }

    //首页数据
    @GetMapping("/getTotalData")
    public Result getTotalData() {
        //获取当前系统用户数量
        long userTotal = userService.count();
        HashMap<String, Object> userMap = new HashMap<>();
        userMap.put("name","用户数量");
        userMap.put("value",userTotal);
        userMap.put("data", new Long[]{userTotal});
        //获取当前系统物业数量
        Long propertyTotal = propertyClient.total();
        HashMap<String, Object> propertyMap = new HashMap<>();
        propertyMap.put("name","物业数量");
        propertyMap.put("value",propertyTotal);
        propertyMap.put("data", new Long[]{propertyTotal});
        //获取投诉数量
        Long complainTotal = complainClient.total();
        HashMap<String, Object> complainMap = new HashMap<>();
        complainMap.put("name","投诉数量");
        complainMap.put("value",complainTotal);
        complainMap.put("data",new Long[]{complainTotal});
        //获取报修数量
        Long repairTotal = houseClient.total();
        HashMap<String, Object> repairMap = new HashMap<>();
        repairMap.put("name","报修数量");
        repairMap.put("value",repairTotal);
        repairMap.put("data",new Long[]{repairTotal});
        ArrayList<Object> list = new ArrayList<>();
        list.add(userMap);
        list.add(propertyMap);
        list.add(complainMap);
        list.add(repairMap);
        return Result.success(list);
    }
    @GetMapping("/getComplainTotal")
    //投诉统计
    public Result getComplainTotal(){
        return Result.success(complainClient.getComplainTotal());
    }
    @GetMapping("/getWeekComplainTotal")
    public Result getWeekComplainTotal(){
        return Result.success(complainClient.getWeekComplainTotal());
    }
    @GetMapping("/getCommonLightTime")
    public Result getCommonLightTime(){
        return Result.success(houseClient.getCommonLightTime());
    }
}
